<!DOCTYPE html>
<html lang=zh>
<head>
    <meta charset="utf-8">
    
    <title>Java技术栈</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="这里用到了Spring Boot + Mybatis + DynamicDataSource配置动态双数据源，可以动态切换数据源实现数据库的读写分离。 添加依赖加入Mybatis启动器，这里添加了Druid连接池、Oracle数据库驱动为例。 1234567891011121314&amp;lt;dependency&amp;gt;	&amp;lt;groupId&amp;gt;org.mybatis.spring.boot&amp;l">
<meta name="keywords" content="Java技术, Spring Boot, Spring Cloud">
<meta property="og:type" content="article">
<meta property="og:title" content="Java技术栈">
<meta property="og:url" content="http://youanyyou.gitee.io/javastack/2018/04/18/Spring Boot/Spring Boot集成Mybatis双数据源/index.html">
<meta property="og:site_name" content="Java技术栈">
<meta property="og:description" content="这里用到了Spring Boot + Mybatis + DynamicDataSource配置动态双数据源，可以动态切换数据源实现数据库的读写分离。 添加依赖加入Mybatis启动器，这里添加了Druid连接池、Oracle数据库驱动为例。 1234567891011121314&amp;lt;dependency&amp;gt;	&amp;lt;groupId&amp;gt;org.mybatis.spring.boot&amp;l">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2017-09-01T02:19:40.368Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java技术栈">
<meta name="twitter:description" content="这里用到了Spring Boot + Mybatis + DynamicDataSource配置动态双数据源，可以动态切换数据源实现数据库的读写分离。 添加依赖加入Mybatis启动器，这里添加了Druid连接池、Oracle数据库驱动为例。 1234567891011121314&amp;lt;dependency&amp;gt;	&amp;lt;groupId&amp;gt;org.mybatis.spring.boot&amp;l">
    

    
        <link rel="alternate" href="/" title="Java技术栈" type="application/atom+xml" />
    

    

    <link rel="stylesheet" href="/javastack/libs/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/javastack/libs/open-sans/styles.css">
    <link rel="stylesheet" href="/javastack/libs/source-code-pro/styles.css">

    <link rel="stylesheet" href="/javastack/css/style.css">

    <script src="/javastack/libs/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/javastack/libs/lightgallery/css/lightgallery.min.css">
    
    
        <link rel="stylesheet" href="/javastack/libs/justified-gallery/justifiedGallery.min.css">
    
    
    
    


</head>

<body>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/javastack/" id="logo">
                <i class="logo"></i>
                <span class="site-title">Java技术栈</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/javastack/.">首页</a>
                
                    <a class="main-nav-link" href="/javastack/archives">归档</a>
                
                    <a class="main-nav-link" href="/javastack/categories">分类</a>
                
                    <a class="main-nav-link" href="/javastack/tags">标签</a>
                
                    <a class="main-nav-link" href="/javastack/about">关于</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="/javastack/css/images/avatar.jpg" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/javastack/',
        CONTENT_URL: '/javastack/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/javastack/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td><a class="main-nav-link" href="/javastack/.">首页</a></td>
                
                    <td><a class="main-nav-link" href="/javastack/archives">归档</a></td>
                
                    <td><a class="main-nav-link" href="/javastack/categories">分类</a></td>
                
                    <td><a class="main-nav-link" href="/javastack/tags">标签</a></td>
                
                    <td><a class="main-nav-link" href="/javastack/about">关于</a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="/javastack/css/images/avatar.jpg" />
            <h2 id="name">Java技术栈</h2><br/>
            <h3 id="title">微信公众号,每日更新！</h3>
            <!--
            <span id="location">
                <i class="fa fa-map-marker"></i>Shenzhen, China
            </span>
            -->
            <a id="follow" target="_blank" href="http://youanyyou.gitee.io/javastack/css/images/avatar.jpg">扫描关注微信公众号</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                113
                <span>文章</span>
            </div>
            <div class="article-info-block">
                58
                <span>标签</span>
            </div>
        </div>
        
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="http://github.com/ppoffice/hexo-theme-icarus" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/javastack/" target="_blank" title="twitter" class=tooltip>
                            <i class="fa fa-twitter"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/javastack/" target="_blank" title="facebook" class=tooltip>
                            <i class="fa fa-facebook"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/javastack/" target="_blank" title="dribbble" class=tooltip>
                            <i class="fa fa-dribbble"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/javastack/" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
        
    </div>
</aside>

            
            <section id="main"><article id="post-Spring Boot/Spring Boot集成Mybatis双数据源" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>这里用到了Spring Boot + Mybatis + DynamicDataSource配置动态双数据源，可以动态切换数据源实现数据库的读写分离。</p>
<h2 id="添加依赖"><a href="#添加依赖" class="headerlink" title="添加依赖"></a>添加依赖</h2><p>加入Mybatis启动器，这里添加了Druid连接池、Oracle数据库驱动为例。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">	&lt;groupId&gt;org.mybatis.spring.boot&lt;/groupId&gt;</span><br><span class="line">	&lt;artifactId&gt;mybatis-spring-boot-starter&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br><span class="line"></span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">	&lt;groupId&gt;com.alibaba&lt;/groupId&gt;</span><br><span class="line">	&lt;artifactId&gt;druid&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br><span class="line"></span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">	&lt;groupId&gt;com.oracle&lt;/groupId&gt;</span><br><span class="line">	&lt;artifactId&gt;ojdbc6&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>
<h2 id="添加启动类"><a href="#添加启动类" class="headerlink" title="添加启动类"></a>添加启动类</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">@EnableMybatis</span><br><span class="line">@EnableTransactionManagement</span><br><span class="line">@SpringBootApplication(exclude = &#123; DataSourceAutoConfiguration.class &#125;)</span><br><span class="line">public class Application &#123;</span><br><span class="line"></span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		SpringApplication.run(ServiceApplication.class, args);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })：<br>这里用到了双数据源，需要排除数据源的自动配置，如果只有一个数据源用Spring Boot的自动配置就行。</p>
<p>@EnableTransactionManagement：开启事务支持。</p>
<p>@EnableMybatis：开启Mybatis功能</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">@Target(ElementType.TYPE)</span><br><span class="line">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="line">@Documented</span><br><span class="line">@Import(MybatisConfig.class)</span><br><span class="line">public @interface EnableMybatis &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="Mybatis配置类"><a href="#Mybatis配置类" class="headerlink" title="Mybatis配置类"></a>Mybatis配置类</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">@MapperScan(basePackages = DSConfig.BASE_PACKAGES)</span><br><span class="line">public class MybatisConfig implements DSConfig &#123;</span><br><span class="line"></span><br><span class="line">	@Primary</span><br><span class="line">	@Bean</span><br><span class="line">	public DynamicDataSource dynamicDataSource(@Qualifier(DB_MASTER) DataSource master,</span><br><span class="line">			@Qualifier(DB_SLAVE) DataSource slave) &#123;</span><br><span class="line">		Map&lt;Object, Object&gt; dsMap = new HashMap&lt;&gt;();</span><br><span class="line">		dsMap.put(DB_MASTER, master);</span><br><span class="line">		dsMap.put(DB_MASTER, slave);</span><br><span class="line"></span><br><span class="line">		DynamicDataSource dynamicDataSource = new DynamicDataSource();</span><br><span class="line">		dynamicDataSource.setDefaultTargetDataSource(master);</span><br><span class="line">		dynamicDataSource.setTargetDataSources(dsMap);</span><br><span class="line">		return dynamicDataSource;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Bean</span><br><span class="line">	public PlatformTransactionManager transactionManager(DynamicDataSource dynamicDataSource) &#123;</span><br><span class="line">		return new DataSourceTransactionManager(dynamicDataSource);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Bean</span><br><span class="line">	public SqlSessionFactory sqlSessionFactory(DynamicDataSource dynamicDataSource)</span><br><span class="line">			throws Exception &#123;</span><br><span class="line">		SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();</span><br><span class="line">		sessionFactory.setDataSource(dynamicDataSource);</span><br><span class="line">		sessionFactory.setMapperLocations(</span><br><span class="line">				((ResourcePatternResolver) new PathMatchingResourcePatternResolver())</span><br><span class="line">						.getResources(DSConfig.MAPPER_LOCATIONS));</span><br><span class="line">		return sessionFactory.getObject();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>DSConfig常量类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">public interface DSConfig &#123;</span><br><span class="line"></span><br><span class="line">	String DS_PREFIX = &quot;spring.datasource&quot;;</span><br><span class="line">	String DS_ACTIVE = &quot;active&quot;;</span><br><span class="line"></span><br><span class="line">	String DB_MASTER = &quot;db-master&quot;;</span><br><span class="line">	String DB_SLAVE = &quot;db-slave&quot;;</span><br><span class="line"></span><br><span class="line">	String DRUID = &quot;druid&quot;;</span><br><span class="line"></span><br><span class="line">	String DRUID_MONITOR_USERNAME = &quot;spring.druid.username&quot;;</span><br><span class="line">	String DRUID_MONITOR_PASSWORD = &quot;spring.druid.password&quot;;</span><br><span class="line">	String DRUID_MONITOR_URL = &quot;/druid/*&quot;;</span><br><span class="line">	String DRUID_FILTER_EXCLUSIONS = &quot;*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*&quot;;</span><br><span class="line">	String DRUID_FILTER_URL = &quot;/*&quot;;</span><br><span class="line"></span><br><span class="line">	String BASE_PACKAGES = &quot;com.example.**.mapper&quot;;</span><br><span class="line">	String MAPPER_LOCATIONS = &quot;mapper/**/*.xml&quot;;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="连接池配置类"><a href="#连接池配置类" class="headerlink" title="连接池配置类"></a>连接池配置类</h2><p>Druid连接池的自动配置类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">@Import(&#123; PropertiesConfig.class &#125;)</span><br><span class="line">@ConditionalOnClass(DruidDataSource.class)</span><br><span class="line">@ConditionalOnProperty(prefix = DSConfig.DS_PREFIX, value = DSConfig.DS_ACTIVE, havingValue = DSConfig.DRUID)</span><br><span class="line">public class DruidAutoConfig implements DSConfig &#123;</span><br><span class="line"></span><br><span class="line">	private Logger logger = LoggerUtils.getLogger(this);</span><br><span class="line"></span><br><span class="line">	@Bean(name = DB_MASTER, initMethod = &quot;init&quot;, destroyMethod = &quot;close&quot;)</span><br><span class="line">	public DataSource dataSourceMaster(DruidMasterProperties masterProperties) throws SQLException &#123;</span><br><span class="line">		logger.debug(&quot;master properties: &#123;&#125;&quot;, masterProperties.toString());</span><br><span class="line"></span><br><span class="line">		DruidDataSource dds = new DruidDataSource();</span><br><span class="line">		dds.setDriverClassName(masterProperties.getDriverClassName());</span><br><span class="line">		dds.setUrl(masterProperties.getUrl());</span><br><span class="line">		dds.setUsername(masterProperties.getUsername());</span><br><span class="line">		dds.setPassword(masterProperties.getPassword());</span><br><span class="line">		dds.setInitialSize(masterProperties.getInitialSize());</span><br><span class="line">		dds.setMinIdle(masterProperties.getMinIdle());</span><br><span class="line">		dds.setMaxActive(masterProperties.getMaxActive());</span><br><span class="line">		dds.setMaxWait(masterProperties.getMaxWait());</span><br><span class="line">		dds.setTimeBetweenEvictionRunsMillis(masterProperties.getTimeBetweenEvictionRunsMillis());</span><br><span class="line">		dds.setMinEvictableIdleTimeMillis(masterProperties.getMinEvictableIdleTimeMillis());</span><br><span class="line">		dds.setValidationQuery(masterProperties.getValidationQuery());</span><br><span class="line">		dds.setTestOnBorrow(masterProperties.isTestOnBorrow());</span><br><span class="line">		dds.setTestWhileIdle(masterProperties.isTestWhileIdle());</span><br><span class="line">		dds.setTestOnReturn(masterProperties.isTestOnReturn());</span><br><span class="line">		dds.setPoolPreparedStatements(masterProperties.isPoolPreparedStatements());</span><br><span class="line">		dds.setMaxPoolPreparedStatementPerConnectionSize(</span><br><span class="line">				masterProperties.getMaxPoolPreparedStatementPerConnectionSize());</span><br><span class="line">		dds.setFilters(masterProperties.getFilters());</span><br><span class="line"></span><br><span class="line">		return dds;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Bean(name = DB_SLAVE, initMethod = &quot;init&quot;, destroyMethod = &quot;close&quot;)</span><br><span class="line">	public DataSource dataSourceSlave(DruidSlaveProperties slaveProperties) throws SQLException &#123;</span><br><span class="line">		logger.debug(&quot;slave properties: &#123;&#125;&quot;, slaveProperties.toString());</span><br><span class="line"></span><br><span class="line">		DruidDataSource dds = new DruidDataSource();</span><br><span class="line">		dds.setDriverClassName(slaveProperties.getDriverClassName());</span><br><span class="line">		dds.setUrl(slaveProperties.getUrl());</span><br><span class="line">		dds.setUsername(slaveProperties.getUsername());</span><br><span class="line">		dds.setPassword(slaveProperties.getPassword());</span><br><span class="line">		dds.setInitialSize(slaveProperties.getInitialSize());</span><br><span class="line">		dds.setMinIdle(slaveProperties.getMinIdle());</span><br><span class="line">		dds.setMaxActive(slaveProperties.getMaxActive());</span><br><span class="line">		dds.setMaxWait(slaveProperties.getMaxWait());</span><br><span class="line">		dds.setTimeBetweenEvictionRunsMillis(slaveProperties.getTimeBetweenEvictionRunsMillis());</span><br><span class="line">		dds.setMinEvictableIdleTimeMillis(slaveProperties.getMinEvictableIdleTimeMillis());</span><br><span class="line">		dds.setValidationQuery(slaveProperties.getValidationQuery());</span><br><span class="line">		dds.setTestOnBorrow(slaveProperties.isTestOnBorrow());</span><br><span class="line">		dds.setTestWhileIdle(slaveProperties.isTestWhileIdle());</span><br><span class="line">		dds.setTestOnReturn(slaveProperties.isTestOnReturn());</span><br><span class="line">		dds.setPoolPreparedStatements(slaveProperties.isPoolPreparedStatements());</span><br><span class="line">		dds.setMaxPoolPreparedStatementPerConnectionSize(</span><br><span class="line">				slaveProperties.getMaxPoolPreparedStatementPerConnectionSize());</span><br><span class="line">		dds.setFilters(slaveProperties.getFilters());</span><br><span class="line"></span><br><span class="line">		return dds;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Bean</span><br><span class="line">	public ServletRegistrationBean druidServletRegistrationBean(EnvConfig env) &#123;</span><br><span class="line">		String username = env.getStringValue(DSConfig.DRUID_MONITOR_USERNAME);</span><br><span class="line">		String password = env.getStringValue(DSConfig.DRUID_MONITOR_PASSWORD);</span><br><span class="line">		return new ServletRegistrationBean(new DruidStatViewServlet(username, password),</span><br><span class="line">				DSConfig.DRUID_MONITOR_URL);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Bean</span><br><span class="line">	public FilterRegistrationBean druidFilterRegistrationBean() &#123;</span><br><span class="line">		WebStatFilter wsf = new WebStatFilter();</span><br><span class="line">		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();</span><br><span class="line">		filterRegistrationBean.setFilter(wsf);</span><br><span class="line">		filterRegistrationBean.setUrlPatterns(Arrays.asList(DSConfig.DRUID_FILTER_URL));</span><br><span class="line">		filterRegistrationBean.setInitParameters(</span><br><span class="line">				Collections.singletonMap(&quot;exclusions&quot;, DSConfig.DRUID_FILTER_EXCLUSIONS));</span><br><span class="line">		return filterRegistrationBean;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>根据类路径下有DruidDataSource这个类即有Druid这个jar包和配置文件中spring.datasource.active=druid才开启对Druid连接池的自动配置。</p>
<p>导入的配置文件：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">@ComponentScan(basePackages = &quot;com.example.common.config.properties&quot;)</span><br><span class="line">public class PropertiesConfig &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>DruidMasterProperties、DruidSlaveProperties属性文件读取的配置省略。</p>
<p>连接池监控配置类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">public class DruidStatViewServlet extends StatViewServlet &#123;</span><br><span class="line"></span><br><span class="line">	private static final long serialVersionUID = 1L;</span><br><span class="line"></span><br><span class="line">	private String username;</span><br><span class="line">	private String password;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public String getInitParameter(String name) &#123;</span><br><span class="line">		if (&quot;loginUsername&quot;.equals(name)) &#123;</span><br><span class="line">			return username;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		if (&quot;loginPassword&quot;.equals(name)) &#123;</span><br><span class="line">			return password;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		return super.getInitParameter(name);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public DruidStatViewServlet(String username, String password) &#123;</span><br><span class="line">		super();</span><br><span class="line">		this.username = username;</span><br><span class="line">		this.password = password;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public String getUsername() &#123;</span><br><span class="line">		return username;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public String getPassword() &#123;</span><br><span class="line">		return password;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在META-INF/spring.factories中加入Druid自动配置映射：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">org.springframework.boot.autoconfigure.EnableAutoConfiguration=\</span><br><span class="line">com.example.common.config.ds.DruidAutoConfig</span><br></pre></td></tr></table></figure>
<h2 id="切换数据源"><a href="#切换数据源" class="headerlink" title="切换数据源"></a>切换数据源</h2><p>切换数据源注解：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">@Target(ElementType.METHOD)</span><br><span class="line">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="line">@Documented</span><br><span class="line">public @interface DS &#123;</span><br><span class="line">	String value() default DSConfig.DB_MASTER;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>动态数据源类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">public class DynamicDataSource extends AbstractRoutingDataSource &#123;</span><br><span class="line"></span><br><span class="line">	private final Logger logger = LoggerUtils.getLogger(this);</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	protected Object determineCurrentLookupKey() &#123;</span><br><span class="line">		logger.debug(&quot;当前数据源为&#123;&#125;&quot;, DataSourceContextHolder.getDS());</span><br><span class="line">		return DataSourceContextHolder.getDS();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>动态数据源AOP实现类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">@Aspect</span><br><span class="line">@Component</span><br><span class="line">public class DynamicDataSourceAspect &#123;</span><br><span class="line"></span><br><span class="line">	@Before(&quot;@annotation(DS)&quot;)</span><br><span class="line">	public void beforeSwitchDS(JoinPoint point) &#123;</span><br><span class="line">		Class&lt;?&gt; className = point.getTarget().getClass();</span><br><span class="line">		String methodName = point.getSignature().getName();</span><br><span class="line">		Class&lt;?&gt;[] argClass = ((MethodSignature) point.getSignature()).getParameterTypes();</span><br><span class="line">		String dataSource = DataSourceContextHolder.DEFAULT_DS;</span><br><span class="line"></span><br><span class="line">		try &#123;</span><br><span class="line">			Method method = className.getMethod(methodName, argClass);</span><br><span class="line">			if (method.isAnnotationPresent(DS.class)) &#123;</span><br><span class="line">				DS annotation = method.getAnnotation(DS.class);</span><br><span class="line">				dataSource = annotation.value();</span><br><span class="line">			&#125;</span><br><span class="line">		&#125; catch (Exception e) &#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">		DataSourceContextHolder.setDS(dataSource);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@After(&quot;@annotation(DS)&quot;)</span><br><span class="line">	public void afterSwitchDS(JoinPoint point) &#123;</span><br><span class="line">		DataSourceContextHolder.clearDS();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>绑定当前线程数据源类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">public class DataSourceContextHolder &#123;</span><br><span class="line"></span><br><span class="line">	public static final String DEFAULT_DS = DSConfig.DB_MASTER;</span><br><span class="line"></span><br><span class="line">	private static final ThreadLocal&lt;String&gt; DS_HOLDER = new ThreadLocal&lt;&gt;();</span><br><span class="line"></span><br><span class="line">	public static void setDS(String dbType) &#123;</span><br><span class="line">		DS_HOLDER.set(dbType);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public static String getDS() &#123;</span><br><span class="line">		return (DS_HOLDER.get());</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public static void clearDS() &#123;</span><br><span class="line">		DS_HOLDER.remove();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">



</div>

    <a data-url="http://youanyyou.gitee.io/javastack/2018/04/18/Spring Boot/Spring Boot集成Mybatis双数据源/" data-id="cjg4zd8os004khg8anj0aclfc" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        // Prevent duplicate binding
        if (typeof(__SHARE_BUTTON_BINDED__) === 'undefined' || !__SHARE_BUTTON_BINDED__) {
            __SHARE_BUTTON_BINDED__ = true;
        } else {
            return;
        }
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="fa fa-twitter article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="fa fa-facebook article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="fa fa-pinterest article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="fa fa-google article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

            
    

        </footer>
    </div>
    
        
<nav id="article-nav">
    
        <a href="/javastack/2018/04/18/Spring Boot/Spring Boot日志集成/" id="article-nav-newer" class="article-nav-link-wrap">
            <strong class="article-nav-caption">上一篇</strong>
            <div class="article-nav-title">
                
                    (no title)
                
            </div>
        </a>
    
    
        <a href="/javastack/2018/04/18/Spring Boot/Spring Boot发布将jar包转为war包。/" id="article-nav-older" class="article-nav-link-wrap">
            <strong class="article-nav-caption">下一篇</strong>
            <div class="article-nav-title"></div>
        </a>
    
</nav>


    
</article>


    
    

</section>
            
                
<aside id="sidebar">
   
        
    <div class="widget-wrap">
        <h3 class="widget-title">分类</h3>
        <div class="widget">
            <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/Java/">Java</a><span class="category-list-count">37</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/Java/多线程/">多线程</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/Java/新特性/">新特性</a><span class="category-list-count">10</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/Maven/">Maven</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/Mybatis/">Mybatis</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/Netty/">Netty</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/Tomcat/">Tomcat</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/书籍推荐/">书籍推荐</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/云计算/">云计算</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/开源项目/">开源项目</a><span class="category-list-count">10</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/测试/">测试</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/漏洞/">漏洞</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/程序人生/">程序人生</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/算法/">算法</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/编程语言/">编程语言</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/行业动态/">行业动态</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/连接池/">连接池</a><span class="category-list-count">2</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">技术栈</h3>
        <div class="widget tagcloud">
            <a href="/javastack/tags/CAT/" style="font-size: 10px;">CAT</a> <a href="/javastack/tags/Cobar/" style="font-size: 10px;">Cobar</a> <a href="/javastack/tags/Cookie/" style="font-size: 10px;">Cookie</a> <a href="/javastack/tags/Disconf/" style="font-size: 10px;">Disconf</a> <a href="/javastack/tags/Druid/" style="font-size: 12.86px;">Druid</a> <a href="/javastack/tags/Eclipse/" style="font-size: 10px;">Eclipse</a> <a href="/javastack/tags/Facebook/" style="font-size: 10px;">Facebook</a> <a href="/javastack/tags/IP/" style="font-size: 10px;">IP</a> <a href="/javastack/tags/IaaS/" style="font-size: 10px;">IaaS</a> <a href="/javastack/tags/JVM/" style="font-size: 10px;">JVM</a> <a href="/javastack/tags/Java/" style="font-size: 20px;">Java</a> <a href="/javastack/tags/Jodd/" style="font-size: 10px;">Jodd</a> <a href="/javastack/tags/Junit/" style="font-size: 10px;">Junit</a> <a href="/javastack/tags/Kotlin/" style="font-size: 10px;">Kotlin</a> <a href="/javastack/tags/LVS/" style="font-size: 10px;">LVS</a> <a href="/javastack/tags/Maven/" style="font-size: 14.29px;">Maven</a> <a href="/javastack/tags/Mybatis/" style="font-size: 10px;">Mybatis</a> <a href="/javastack/tags/NIO/" style="font-size: 10px;">NIO</a> <a href="/javastack/tags/Netty/" style="font-size: 10px;">Netty</a> <a href="/javastack/tags/Nginx/" style="font-size: 10px;">Nginx</a> <a href="/javastack/tags/Oracle/" style="font-size: 11.43px;">Oracle</a> <a href="/javastack/tags/PaaS/" style="font-size: 10px;">PaaS</a> <a href="/javastack/tags/Python/" style="font-size: 10px;">Python</a> <a href="/javastack/tags/SaaS/" style="font-size: 10px;">SaaS</a> <a href="/javastack/tags/Squid/" style="font-size: 10px;">Squid</a> <a href="/javastack/tags/Tengine/" style="font-size: 10px;">Tengine</a> <a href="/javastack/tags/Thrift/" style="font-size: 10px;">Thrift</a> <a href="/javastack/tags/Tomcat/" style="font-size: 12.86px;">Tomcat</a> <a href="/javastack/tags/https/" style="font-size: 10px;">https</a> <a href="/javastack/tags/jdk10/" style="font-size: 10px;">jdk10</a> <a href="/javastack/tags/jdk7/" style="font-size: 10px;">jdk7</a> <a href="/javastack/tags/jdk8/" style="font-size: 17.14px;">jdk8</a> <a href="/javastack/tags/jdk9/" style="font-size: 10px;">jdk9</a> <a href="/javastack/tags/书籍/" style="font-size: 15.71px;">书籍</a> <a href="/javastack/tags/云计算/" style="font-size: 10px;">云计算</a> <a href="/javastack/tags/代理/" style="font-size: 10px;">代理</a> <a href="/javastack/tags/分布式/" style="font-size: 11.43px;">分布式</a> <a href="/javastack/tags/区块链/" style="font-size: 10px;">区块链</a> <a href="/javastack/tags/多线程/" style="font-size: 12.86px;">多线程</a> <a href="/javastack/tags/安全/" style="font-size: 10px;">安全</a> <a href="/javastack/tags/开源项目/" style="font-size: 18.57px;">开源项目</a> <a href="/javastack/tags/性能优化/" style="font-size: 10px;">性能优化</a> <a href="/javastack/tags/攻击/" style="font-size: 10px;">攻击</a> <a href="/javastack/tags/数据库/" style="font-size: 10px;">数据库</a> <a href="/javastack/tags/架构师/" style="font-size: 11.43px;">架构师</a> <a href="/javastack/tags/测试/" style="font-size: 10px;">测试</a> <a href="/javastack/tags/漏洞/" style="font-size: 11.43px;">漏洞</a> <a href="/javastack/tags/监控/" style="font-size: 11.43px;">监控</a> <a href="/javastack/tags/程序人生/" style="font-size: 12.86px;">程序人生</a> <a href="/javastack/tags/算法/" style="font-size: 11.43px;">算法</a> <a href="/javastack/tags/缓存/" style="font-size: 10px;">缓存</a> <a href="/javastack/tags/编程语言/" style="font-size: 10px;">编程语言</a> <a href="/javastack/tags/腾讯/" style="font-size: 10px;">腾讯</a> <a href="/javastack/tags/行业动态/" style="font-size: 10px;">行业动态</a> <a href="/javastack/tags/负载均衡/" style="font-size: 11.43px;">负载均衡</a> <a href="/javastack/tags/连接池/" style="font-size: 12.86px;">连接池</a> <a href="/javastack/tags/阿里巴巴/" style="font-size: 14.29px;">阿里巴巴</a> <a href="/javastack/tags/高并发/" style="font-size: 10px;">高并发</a>
        </div>
    </div>

    
        
    <div class="widget-wrap widget-list">
        <h3 class="widget-title">链接</h3>
        <div class="widget">
            <ul>
                
                    <li>
                        <a href="http://hexo.io">Hexo</a>
                    </li>
                
            </ul>
        </div>
    </div>


    
    <div id="toTop" class="fa fa-angle-up"></div>
</aside>

            
        </div>
        <footer id="footer">
    <div class="outer">
        <div id="footer-info" class="inner">
            &copy; 2018 Java技术栈 版权所有
            <br>
            Powered by <a href="http://www.javastack.cn/" target="_self">javastack.cn</a>. 
        </div>
    </div>
</footer>
        


    
        <script src="/javastack/libs/lightgallery/js/lightgallery.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-thumbnail.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-pager.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-autoplay.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-fullscreen.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-zoom.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-hash.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-share.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-video.min.js"></script>
    
    
        <script src="/javastack/libs/justified-gallery/jquery.justifiedGallery.min.js"></script>
    
    



<!-- Custom Scripts -->
<script src="/javastack/js/main.js"></script>

    </div>
</body>
</html>